/**
 * Created by wxj on 2017/4/12.
 */
$(function () {
  	var bdbPlicyManage = {
		/* 初始数据 */
		defData: {
			pageSize: 20
		},

		/* 页面状态 */
		pageState: {
			  page: 1,
			  search: '',
		      nodeId: '',
			  noData: 'def'
		},
		resetPageState: function() {
			this.pageState = {
				search: '',
				page: 1,
				noData: 'def'
			};

			this.list();
		},

		/* 添加策略 */
		addEvent: function() {
			var _this = this,
				addVerifyObj;

			addVerifyObj = $('#bdb-policyManage-add-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
						error.appendTo(element.parents(".bdb-vc"));
					} else {
						error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.addSubmit(form);
				}
			});

			$('#bdb-add-policyManage').off('click').on("click", function() {
				bdbMain.mLRManag({mask: false, loading: false});
				_this.addFormFill(addVerifyObj);
			});
		},

	  	/* 添加填充 */
	    addFormFill: function(addVerifyObj) {
	      	var _this = this,
				ele = $('#bdb-policyManage-add-form');

			// 显示ring-chart
		  	_this.resetChartRing('add');
			ele.find('#getCanvasAdd').bdbCanvasChart({
				totalPercent: 0,
				serverPercent: 0
			});

			// 填充优先级顺序
		  	var priorityListAdd = ele.find('#js-sort-list-add');
		    priorityListAdd.html('');
			var itemsSpanSel = _this.priorityList('add');
		    priorityListAdd.html(itemsSpanSel);
		    ele.find('.sort-item').arrangeable();

			_this.ringFillEvent(ele);

			$(".bdbBlankEle").bdbDialog({
				ele: '#bdb-policyManage-add-dialog',
				formObj: addVerifyObj,
				form: $('#bdb-policyManage-add-form'),
				reset: true
			});
		},

		/* 提交添加的服务器组 */
		addSubmit: function(form) {
			var _this = this,
				form = $(form);

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/Policy/addPolicy', {
				policy_name: form.find("#policyNameAdd").val(),
				server_weight: form.find("#serverWeightAdd").val(),
				cost_weight: form.find("#costWeightAdd").val(),
				is_minimum: form.find("#firstGuaranteeAdd").val(),
				ip_num: form.find("#IPNumAdd").val(),
				mini_usability: form.find("#minAvailAdd").val(),
			    same_isp: $('#same_isp_add').index() + 1,
			    same_province: $('#same_province_add').index() + 1,
				other_isp:$('#other_isp_add').index() + 1,
				other_province:$('#other_province_add').index() + 1
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '添加成功.'}});
					bdbMain.mLSleep({}, function() {
						_this.resetPageState();
					});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert:{type: 2, msg: response.msg}});
				}
				bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

		/* 策略管理列表 */
		list: function(obj) {
			var _this = this,
				obj = obj || {page: 1};

			_this.pageState.page = obj.page;
			bdbMain.mLRManag({mask: false, partMask: true});

			$.post('/Policy/policyList', {
			    pageNumber: _this.pageState.page,
				pageSize: _this.defData.pageSize,
				query: _this.pageState.search
			}, function(response) {
				var totalRowCnt = 0;
				if (response.code == 0) {
					bdbMain.mLRManag({partMask: false, loading: false});
					var listHtml = _this.listProc(response.data);
					totalRowCnt = response.data.totalCount;
					_this.listNull(totalRowCnt);
					$('.bdb-list').html(listHtml);

					// 分页插件展示
					$('#js-bdb-creatPage').bdbPagination({
						totalRowCnt: totalRowCnt,
						currentPage: _this.pageState.page,
						pageSize: _this.defData.pageSize
					});
					$('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}',totalRowCnt));

				} else {
				  	bdbMain.mLRManag({partMask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}
			});
		},

		/* 列表模板 */
		listProc: function(data) {
			var tpl = '',
				optionChange = '';
			$.each(data.list, function(index, value) {
			  	var isConnected = value.is_connected,
					isMiniText = value.is_minimum == 1 ? '是' :'否';

			    optionChange = isConnected  == 1 ?  '<a class="node-set" href="javascript:void(0)">编辑</a></div><div class="bdb-connected-menu"><img class="bdb-isConnected-icon" src="/static/imgs/global/yinyong.svg"><span>已引用</span></div>': '<a class="node-set" href="javascript:void(0)">编辑</a><div class="v-line-ffa007"></div><a class="bdb-mgn-l--1 bdb-f-c-c8baac node-del" href="javascript:void(0)">删除</a></div>';
				tpl += '<div class="bdb-list-row" data-id="' + value.policy_id + '">\
							  <div class="bdb-mx-w-col-1 bdb-ellipsis">' + value.policy_id + '</div>\
							  <div class="bdb-mx-w-col-2 bdb-ellipsis">' + value.policy_name + '</div>\
							  <div class="bdb-mx-w-col-3 bdb-ellipsis">' + value.server_weight + '</div>\
							  <div class="bdb-mx-w-col-4 bdb-ellipsis">' + value.cost_weight + '</div>\
							  <div class="bdb-mx-w-col-5 bdb-ellipsis">' + isMiniText+ '</div>\
							  <div class="bdb-mx-w-col-6 bdb-ellipsis">' + value.ip_num + '</div>\
							  <div class="bdb-mx-w-col-7">\
							  <div class="bdb-option-btn  bdb-p-r bdb-mgn-t-10">'+ optionChange +'</div>\
						</div>';
			});
			return tpl;
		},

		/* 页面没有数据 */
		listNull: function(totalRowCnt) {
			var noResult = $('.bdb-no-result'),
				noSearchRecord = $('.bdb-no-search-record');

			if (totalRowCnt <= 0) {
				if (this.pageState.noData == 'search') { // 查询无结果
					noResult.hide();
					noSearchRecord.show();
				} else { // 暂无记录.
					noResult.show();
					noSearchRecord.hide();
				}
			} else {
				noResult.hide();
				noSearchRecord.hide();
		  }
		},

		/* 编辑 */
		editEvent: function(dataId) {
			var _this = this,
				modifyVerifyObj;

			modifyVerifyObj = $('#bdb-policyManage-edit-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
				  error.addClass("help-block");
				  if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
					  error.appendTo(element.parents(".bdb-vc"));
				  } else {
					  error.insertAfter(element);
				  }
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.modifySubmit(form);
				}
			});

			$.post('/Policy/editPolicyInit', {
			  'policy_id': dataId
			}, function(response) {
				if (response.code == 0) {
					bdbMain.mLRManag({mask: false, loading: false});
					_this.editFormFill(modifyVerifyObj, response.data);
				} else {
					bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}
			});
		},

	  	/* 填充编辑内容 */
	    editFormFill: function(verifyObj, data) {
	      	var _this = this,
				ele = $('#bdb-policyManage-edit-form');

			ele.find("#policyNameEdit").val(data.policy_name);
		    ele.find("#serverWeightEdit").val(data.server_weight);
		    ele.find("#costWeightEdit").val(data.cost_weight);
		    ele.find("#minAvailEdit").val(data.mini_usability);
		    ele.find("#IPNumEdit").val(data.ip_num);

		  	// 填充是否保底
			ele.find('#firstGuaranteeEdit').val(data.is_minimum);

		  	// 填充ring-chart
		    _this.resetChartRing('edit');
			$("#getCanvasEdit").bdbCanvasChart({
			  totalPercent: 100,
			  serverPercent: data.server_weight
			});
			_this.ringFillEvent(ele);

		  	// 填充优先级顺序
		    var priorityListEdit = $('#js-sort-list-edit');
		    priorityListEdit.empty();

		    var sortArr = [];
		    sortArr[data.other_isp - 1] = 'otherIsp';
		    sortArr[data.other_province - 1] = 'otherProvince';
		    sortArr[data.same_isp - 1] = 'sameIsp';
		    sortArr[data.same_province - 1] = 'sameProvince';

		  	var itemsSpanSel = _this.priorityList('edit', sortArr);
		    priorityListEdit.html(itemsSpanSel);

		    // 调用拖拽
			$('.sort-item').arrangeable();

			$(".bdbBlankEle").bdbDialog({
				ele: '#bdb-policyManage-edit-dialog',
				formObj: verifyObj,
				form: $('#bdb-policyManage-edit-form'),
				reset: false
			});
		},

	    priorityList: function(type, sortArr) {
			var prioritySort = ['sameIsp', 'sameProvince', 'otherProvince', 'otherIsp'],
				priorityEleList = {
					'sameIsp': '<span class="sort-item" id="same_isp_' + type + '" >本ISP本省</span>',
					'sameProvince': '<span class="sort-item" id="same_province_' + type + '">跨ISP本省</span>' ,
					'otherProvince': '<span class="sort-item" id="other_province_' + type + '">本ISP跨省</span>',
					'otherIsp': '<span class="sort-item" id="other_isp_' + type + '">跨ISP跨省</span>'
				},
				resultHtml = '';

			if (type != 'add') {
				prioritySort = sortArr;
			}

			$.each(prioritySort, function(i, n) {
			  	if (typeof priorityEleList[n] != "undefined") {
				  	resultHtml += priorityEleList[n];
				}
			});

			return resultHtml;
		},

		/* 提交编辑 */
		modifySubmit: function(form) {
			var _this = this,
				form = $(form);

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/Policy/editPolicy', {
			    policy_id: _this.pageState.nodeId,
				policy_name: form.find("#policyNameEdit").val(),
				server_weight: form.find("#serverWeightEdit").val(),
				cost_weight: form.find("#costWeightEdit").val(),
				is_minimum: form.find("#firstGuaranteeEdit").val(),
				ip_num: form.find("#IPNumEdit").val(),
				mini_usability: form.find("#minAvailEdit").val(),
				same_isp: $('#same_isp_edit').index() + 1,
				same_province: $('#same_province_edit').index() + 1,
				other_isp:$('#other_isp_edit').index() + 1,
				other_province:$('#other_province_edit').index() + 1
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '修改成功.'}});
					_this.list({page: _this.pageState.page});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
				}
				bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

		/* 删除 */
		delEvent: function(dataID) {
			var _this = this;
			bdbMain.confirm({
				textInfo: {
					content: '确定要删除吗？',
					btn: {
						ok: '删除',
						cancel: '取消'
					}
				},
				callback: function(ele, params) {
					_this.delProc(ele, dataID);
				}
			});
		},

		/* 删除请求 */
		delProc: function(ele, dataID) {
			var _this = this;
		  	ele.hide();

			// 请求已发出.
			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return ;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0;
			$.post('/Policy/deletePolicy', {
				'policy_id': dataID
			}, function(res) {
				if (res.code == 0) {
				    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 1, msg: '删除成功'}});
					bdbMain.mLSleep({}, function() {
					 	_this.list({page: bdbMain.pageCheck(_this.pageState.page)});
					});
				} else {
				    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: res.msg}});
				}

			  	bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

	  	/* chart-ring输入百分比填充 */
	  	ringFillEvent: function(ele) {
		  	var _this = this;

			ele.find('#serverWeightAdd, #serverWeightEdit, #costWeightAdd, #costWeightEdit').off('keyup').on('keyup', function (e) {
			  	var thisText = (this.value = this.value.replace(/\D/g,'')), // 禁止输入除了数字外的字符
					thisId = $(this).attr('id');

			  	// 判断如果大于100，按照100计算
			  	if (thisText > 100){
					thisText = (this.value = 100);
				}

			  	if (thisId == 'serverWeightAdd' || thisId == 'costWeightAdd') {
				  	$('#serverWeightAdd-error, #costWeightAdd-error').remove(); // 清除二者的错误提示

				  	if (thisId == 'serverWeightAdd') {
					    $('#costWeightAdd').val(100 - thisText);
					} else if (thisId == 'costWeightAdd') {
					    $('#serverWeightAdd').val(100 - thisText);
					}

					_this.resetChartRing('add');
					$("#getCanvasAdd").bdbCanvasChart({
						totalPercent: 100,
						serverPercent: !!($('#serverWeightAdd').val()) ? $('#serverWeightAdd').val() : 0
					});

				} else if (thisId == 'serverWeightEdit' || thisId == 'costWeightEdit') {
					$('#serverWeightEdit-error, #costWeightEdit-error').remove(); // 清除二者的错误提示

				  	if (thisId == 'serverWeightEdit') {
					    $('#costWeightEdit').val(100 - thisText);
					} else if (thisId == 'costWeightEdit') {
					   $('#serverWeightEdit').val(100 - thisText);
				    }

					_this.resetChartRing('edit');
					$("#getCanvasEdit").bdbCanvasChart({
						totalPercent: 100,
						serverPercent: !!($('#serverWeightEdit').val()) ? $('#serverWeightEdit').val() : 0
					});
				}
			})
		},

	  	/* 重置chart-ring */
	  	resetChartRing: function (type) {
			if (type == 'add') {
				// 重置添加的ring
				$("#getCanvasAdd").remove();
				$('.fillFatherAdd').html('<canvas id="getCanvasAdd" width="130" height="130"></canvas>');
			} else {
				// 重置编辑的ring
				$("#getCanvasEdit").remove();
				$('.fillFatherEdit').html('<canvas id="getCanvasEdit" width="130" height="130"></canvas>');
			}
		},

		/* 列表item操作button */
		listEvent: function() {
			var _this = this;
			$('.bdb-list').off('click').on('click', '.bdb-option-btn', function(e) {
				var ele = $(e.target),
					dataId = ele.parents('.bdb-list-row').attr('data-id');
				_this.pageState.nodeId = dataId;

				if (ele.hasClass('node-set')) {
					_this.editEvent(dataId);
				} else if(ele.hasClass('node-del')) {
					_this.delEvent(dataId);
				}
			});
		},

		/* 搜索事件 */
		searchEvent: function() {
			var _this = this,
				searchInputEle = $('.bdb-search-input');

			searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
				var _cThis = $(this),
					_btnEle = $(this).parent().find('span');

				if (!_btnEle.hasClass('search-clear')) {
					_cThis.animate({width: '240px'}, 500);
					_btnEle.animate({ left : 240 }, 500, function() {
						_btnEle.removeClass('search-gray').addClass('search-blue');
					});
				}
			});

			searchInputEle.off('click').on('click', 'span', function(e) {
				var left = parseInt($(this).css('left'));
				if ($(this).hasClass('search-blue') && left > 0 ) {
					_this.pageState.search = searchInputEle.find('.search-text').val();
					_this.pageState.noData = 'search';
					$(this).removeClass('search-blue').addClass('search-clear');
					_this.list();
				} else if (left > 0){
					searchInputEle.find('.search-text').val('');
					_this.pageState.noData = 'def';
					_this.pageState.search = '';
					$(this).removeClass('search-clear').addClass('search-blue');
					_this.list();
				}
			});
		},

		/* 加载分页 */
		pageEvent: function() {
			var _this = this;
			$('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
				e.preventDefault();
				var page = parseInt($(e.target).text());
				if(!isNaN(page)) {
					_this.list({page: page});
				}
			});
		},

		/* 页面高度resize */
		contentSizeResize: function() {
			$(window).resize(function() {
				$('.bdb-list').bdbScreenH(1);
			});
		},
		init: function() {
			var _this = this;

		    _this.list();
		    _this.addEvent();
		    _this.listEvent();
		    _this.searchEvent();
		    _this.pageEvent();
			_this.contentSizeResize();

			$('.bdb-list').bdbScreenH(1);

		}
	};

	bdbPlicyManage.init();
});